<template>
  <a-tabs @change="changeTab" >
    <a-tab-pane key="0" title="全部">
    </a-tab-pane>
    <a-tab-pane key="1" title="待跟进的需求单">
    </a-tab-pane>
    <a-tab-pane key="2" title="待服务的需求单">
    </a-tab-pane>
  </a-tabs>
  <ProTable
    :columns="columns"
    :request="(params)=> getDemandList({...params,condition:{...params,demandStatus:demandStatus || params.demandStatus ,serviceStatus,  startDate: params.startDate? params.startDate[0]||'' : '', endDate:params.startDate? params.startDate[1]||'' : '',reservationStartTime: params.reservationTime? params.reservationTime[0]||'' : '', reservationEndTime:params.reservationTime? params.reservationTime[1]||'' : ''}})"
    row-key="id"
    :header-title="false"
    :scroll="{ x: 2700 }"
    :action-ref="setActionRef"
    :form-ref="setFormRef"
    :search="{collapsed:false ,span: 4 }"
    :defaultFormData="{startDate:'',endDate:''}"
  >
  <template #demandNo="{ record }">
   
    <a-typography-paragraph copyable :style="{margin:0}">
        <a-link type="text" @click="handleEdit(record)">
        {{ record.demandNo }}
      </a-link>
  </a-typography-paragraph >
  </template>
    <template #option-render="{ dom ,form }">
      <component :is="dom[1]" />
      <component :is="dom[0]" />
      <a-button v-auth="'exportrequirementBtn'" key="search" type="primary" @click="exportHandle(form)">导出</a-button>
      <a-button v-auth="'requirementCreateBtn'"  key="primary" type="primary" @click="handleCreate">创建需求</a-button>
    </template>
    
    <template #requirementRecord="{ record }">
      <a @click="showRecordModal(record)">查看记录</a>
    </template>

    <template #operation="{ record }">
      <a-popconfirm  content="确认发起支付么"  @ok="handlePay(record)">
        <a-button v-auth="'initiatePayBtn'" :disabled="record.orderPrice===0" type="text">发起支付</a-button>
      </a-popconfirm>
      <a-button v-auth="'initiatePayBtn'" @click="handleShort(record)"  v-show="(record.productType===1 && record. chargeType ===3) || (record.productType===2 && record. chargeType ===3) || (record.productType===3 && record. chargeType ===3) || (record.productType === 4 && ( record.chargeType === 4 || record.chargeType === 1 || record.chargeType === 2 || record.chargeType === 6)) " type="text">确认服务</a-button>
      <a-button v-auth="'followUpLogBtn'" type="text" @click="handleEdit(record)">修改</a-button>
      <!-- <a-popconfirm content="确认删除么"  @ok="handleDelete(record)">
      </a-popconfirm> -->
      <a-dropdown>
      <a-button type="text">更多</a-button>
      <template #content>
        <a-doption v-auth="'getPayUrlBtn'"> <a-button type="text" @click="handleAcquire(record)">获取支付链接</a-button></a-doption>
        <a-doption v-auth="'upgradeBtn'" >  <a-button type="text" @click="handleUpgrade(record)" >需求单升级</a-button></a-doption>
        <a-doption v-auth="'followUpTaskBtn'" > <a-button type="text" @click="handleSetTask(record)">设定跟进任务</a-button></a-doption>
        <a-doption v-auth="'followUpLogBtn'" > <a-button type="text" @click="handleHistory(record)">历史跟进记录</a-button></a-doption>
        <a-doption v-auth="'followUpLogBtn'" >   <a-button  type="text" @click="messageStatus(record)">短信状态</a-button></a-doption>
      </template>
    </a-dropdown>

    </template>
  </ProTable>

  <!-- 需求记录弹窗 -->
  <a-modal v-model:visible="recordModalVisible" title="需求记录" @ok="recordModalVisible = false">
    <div v-if="selectedRecord">
      <!-- <p>{{ selectedRecord.requirementRecord }}</p>
      <img v-if="selectedRecord.fileList && selectedRecord.fileList[0]" :src="selectedRecord.fileList[0].filePath" alt="需求记录图片" /> -->
    </div>
  </a-modal>

  <!-- 历史跟进计划弹窗 -->
  <a-modal v-model:visible="historyModalVisible" title="历史跟进计划" @ok="historyModalVisible = false" :width="800">
    <!-- <a-button @click="handleSetTask"> 添加跟进计划 </a-button> -->
    <a-table :columns="historyColumns" :data="historyList" row-key="id">
      <template #operation="{ column, record }">
          <a-button type="text" @click="handleHistoryDetail(record)">修改</a-button>
          <a-popconfirm content="确认删除么"  @ok="handleHistoryDelete(record.id)">
        <a-button status="danger" type="text">删除</a-button>
        </a-popconfirm>
      </template>
    </a-table>
  </a-modal>

  <!-- 需求升级弹窗 -->
  <a-modal v-model:visible="upgradeModalVisible" title="需求升级" @ok="handleUpgradeSubmit" @cancel="upgradeModalVisible = false">
    <a-form :model="upgradeForm" layout="vertical">
      <a-form-item label="指派人" required>
        <a-select v-model="upgradeForm.assignUserId">
          <a-option v-for="item in expertList" :value="item.userId">{{ item.name }}</a-option>
        </a-select>
      </a-form-item>
      <!-- <a-form-item label="指派人名称" required>
        <a-input v-model="upgradeForm.assignUserName" />
      </a-form-item> -->
      <a-form-item label="备注">
        <a-textarea v-model="upgradeForm.remark" />
      </a-form-item>
    </a-form>
  </a-modal>

  <!-- 设定跟进任务弹窗 -->
  <a-modal v-model:visible="taskModalVisible" title="设定跟进任务" @ok="handleTaskSubmit" @cancel="taskModalVisible = false">
    <a-form ref="taskFormRef" :model="taskForm" layout="vertical">
      <!-- <a-form-item label="跟进方式" required>
        <a-select v-model="taskForm.followUpType">
          <a-option value="1">方式1</a-option>
          <a-option value="2">方式2</a-option>
        </a-select>
      </a-form-item> -->
      <a-form-item label="计划日期" required>
        <a-date-picker v-model="taskForm.planDate" :disabledDate="(current) => dayjs(current).isBefore(dayjs().add(-1, 'day'))" />
      </a-form-item>
      <a-form-item label="完成日期" required>
        <a-date-picker v-model="taskForm.finishDate" :disabledDate="(current) => dayjs(current).isBefore(dayjs(taskForm.planDate))" />
      </a-form-item>
      <a-form-item label="说明">
        <a-textarea v-model="taskForm.planInfo" />
      </a-form-item>
    </a-form>
  </a-modal>


  <a-drawer v-model:visible="detailModalVisible" title="需求详情" @ok="saveDemandForm" :width="900">
    <a-descriptions title="客户信息" bordered>
      <a-descriptions-item label="客户姓名">{{ detailData.demandPersonName }}</a-descriptions-item>
      <a-descriptions-item label="CID">{{ detailData.cid }}</a-descriptions-item>
      <a-descriptions-item label="客户电话">{{ detailData.demandPersonPhone }}</a-descriptions-item>
      <a-descriptions-item label="客户座机">{{ detailData.demandPersonLandlinePhone }}</a-descriptions-item>
      <a-descriptions-item label="客户标签">{{ detailData.demandPersonTag }}</a-descriptions-item>
      <a-descriptions-item label="客户地址">{{ detailData.demandPersonAddress }}</a-descriptions-item>
      <a-descriptions-item label="需求类型">{{ detailData.typeName }}</a-descriptions-item>
      <a-descriptions-item label="需求渠道">{{ detailData.channelName }}</a-descriptions-item>
      <a-descriptions-item label="四级分类">{{ detailData.fourTypeName }}</a-descriptions-item>
    </a-descriptions>

    <a-descriptions title="服务订单信息" bordered style="margin-top: 20px;">
      <a-descriptions-item label="联系人">{{ detailData.contactName }}</a-descriptions-item>
      <a-descriptions-item label="联系人电话">{{ detailData.contactPhone }}</a-descriptions-item>
      <a-descriptions-item label="联系人地址">{{ detailData.contactAddress }}</a-descriptions-item>
      <a-descriptions-item label="预约时间">{{ detailData.reservationTime }}</a-descriptions-item>
      <a-descriptions-item label="服务项目">{{ detailData.productType === 1 ? '保洁':  detailData.productType === 2 ? '搬家' : detailData.productType === 3 ? '保养' : detailData.productType === 4 ? '维修' : '未知' }}</a-descriptions-item>
      <a-descriptions-item label="收费类型">{{ detailData.chargeType === 1 ? '面单订单':  detailData.chargeType === 2 ? '内部员工' : detailData.chargeType === 3 ? '家装订单' : detailData.productType === 4 ? '保内' : detailData.productType === 5 ? '保外' : '未知' }}</a-descriptions-item>
      <a-descriptions-item label="订单金额">{{ detailData.orderPrice }}</a-descriptions-item>
      <a-descriptions-item label="需求记录">{{ detailData.requirementRecord }}</a-descriptions-item>
      <a-descriptions-item label="需求状态">{{ detailData.demandStatus === 1 ? '跟进中' : '已完成' }}</a-descriptions-item>
      <a-descriptions-item label="备注">{{ detailData.carefulRemark }}</a-descriptions-item>
    </a-descriptions>

    <a-descriptions title="服务产品列表" bordered style="margin-top: 20px;">
      <a-descriptions-item label="产品名称" v-for="product in detailData.productList" :key="product.id">
        {{ product.productName }} - {{ product.productSpecName }}
      </a-descriptions-item>
    </a-descriptions>
    <a-descriptions v-if="detailData.productList && detailData.productList.length == 0" title="服务内容" bordered style="margin-top: 20px;">
      <a-descriptions-item label="添加服务">  <ServiceReservation  v-model="serviceReservationData" /></a-descriptions-item>
    </a-descriptions>

    <a-descriptions title="需求记录" bordered style="margin-top: 20px;">
    <a-descriptions-item label="上传"> 
      <UploadFile v-model="detailData.fileList"></UploadFile>
    </a-descriptions-item>
    <a-descriptions-item label="记录"> 
      <a-textarea  v-model="detailData.requirementRecord"/>
    </a-descriptions-item>
    </a-descriptions>
    <a-descriptions title="订单状态" bordered style="margin-top: 20px;">
      <a-descriptions-item label="状态" >
        <a-select v-model="detailData.demandStatus" >
          <a-option :value="1">待跟进</a-option>
          <a-option :value="2">已跟进</a-option>
          <a-option :value="3">已完成</a-option>
        </a-select>
      </a-descriptions-item>
    </a-descriptions>
    
  </a-drawer>
      <a-modal v-model:visible="isSmsStatusVisible" title="短信状态" width="80%" >
          <ProTable  :pagination="false"  :columns="smsStatusColumns" :action-ref="setActionRefm" :request="(params) => getSmsStatusList(demandId)"  :search="false"
          header-title="">
          </ProTable>
        </a-modal>

</template>

<script setup lang="ts">
import { onMounted, Ref, ref } from 'vue';
import { useRouter } from 'vue-router';
import { getDemandList, saveDemand, deleteDemand, getPayUrl, getDemandFollowUpList, saveDemandComplaint, saveDemandFollowUp, sendPaySms, deleteDemandFollowUp, getDemandDetail,updateDemandPlan,getSmsStatusList,confirmServiceSms } from '@/api/demand'; // 假设你已经定义了这些API
import Message from '@arco-design/web-vue/es/message';
import { getExpertList } from '@/api/demandComplaint';
import dayjs from 'dayjs';
import UploadFile from '@/components/FileUpload/index.vue';
import ServiceReservation from '@/components/ServiceSelection/index.vue'; // 

const router = useRouter();
const demandStatus = ref('');
const serviceStatus = ref('');
const expertList = ref<{ userId: number; name: string }[]>([]);
const formRef = ref();
const actionRef = ref();
const tabKey = ref('0')
const demandId = ref(1);
const setFormRef = (ref: Ref) => {
  formRef.value = ref;
};
const serviceReservationData = ref({
  productType: 0,
  service: "",
  chargeType: 0,
  productList: [],
});
const setActionRef = (ref: Ref) => {
  actionRef.value = ref;
};
const isSmsStatusVisible = ref(false);
const actionRefm = ref();

const setActionRefm = (ref) => {
    actionRefm.value = ref;
};
const taskFormRef = ref();
const changeTab = (key: string ) => {
  tabKey.value = key;
  if (key === '0') {
    demandStatus.value = '';
    serviceStatus.value = '';
  } else if (key === '1') {
    demandStatus.value = '1';
    serviceStatus.value = '';
  } else if (key === '2') {
    demandStatus.value = '';
    serviceStatus.value = '1';
  }
  formRef.value.submit();
};

onMounted(async () => {
  const res = await getExpertList();
  expertList.value = res.data;
  console.log(expertList.value, '专家列表');
});
const messageStatus = (record)=>{

       demandId.value = record.id
        isSmsStatusVisible.value = true
        actionRefm.value.reload();
      }
const exportHandle = async (form) => {
  const params = form.value.model;
   const obj = {...params,demandStatus:demandStatus.value || params.demandStatus || '' ,serviceStatus:serviceStatus.value,  startDate: params.startDate? params.startDate[0]||'' : '', endDate:params.startDate? params.startDate[1]||'' : '',reservationStartTime: params.reservationTime? params.reservationTime[0]||'' : '', reservationEndTime:params.reservationTime? params.reservationTime[1]||'' : ''}
  const url  = new URLSearchParams(obj).toString();
  window.open('/service/demand/downloadDemandExcel?'+url);
};

const smsStatusColumns = [
    {
        title: '需求ID',
        dataIndex: 'demandId',
        key: 'demandId',
        width: 100,
    },
    {
        title: '短信内容',
        dataIndex: 'content',
        key: 'content',
        width: 300,
        ellipsis:true
    },
    {
        title: '手机号',
        dataIndex: 'phone',
        key: 'phone',
    },
    {
        title: '发送时间',
        dataIndex: 'sendTime',
        key: 'sendTime',
    },
    {
        title: '接收时间',
        dataIndex: 'receiveDate',
        key: 'receiveDate',
    },
    {
        title: '发送状态',
        dataIndex: 'sendStatus',
        key: 'sendStatus',
        valueEnum:{
        1: { text: '等待回执' },
        2: { text: '发送失败' },
        3: { text: '发送成功' },
        4: { text: '未知状态' },
      }
    },
    {
        title: '发送流水号',
        dataIndex: 'bizId',
        key: 'bizId',
        ellipsis:true
    },
    ];
// 定义列
const columns = [
  { title: '创建日期', dataIndex: 'startDate', key: 'startDate', hideInTable: true, valueType: 'dateRange' },
  { title: '需求单号', dataIndex: 'demandNo', key: 'demandNo', ellipsis: true, width: 300 ,slotName: 'demandNo',copyable:true },
  {
    title: 'CID',dataIndex: 'cid',key:'cid',ellipsis:true
  },
  {
    title:'联系人城市',dataIndex:'contactCity',hideInTable: true
  },
  {
    title:'姓名/手机',dataIndex:'contact',hideInTable: true
  },
  // { title: '创建结束日期', dataIndex: 'endDate', key: 'endDate', hideInTable: true, valueType: 'date' },
  
  { title: '预约日期', dataIndex: 'reservationTime', key: 'reservationTime', valueType: 'dateRange' ,ellipsis:true},
  { title: '创建时间', dataIndex: 'createTime', key: 'createTime', valueType: 'date', width: 200, hideInSearch: true },
  { title: '需求类型', dataIndex: 'typeName', key: 'typeName', hideInSearch: true ,ellipsis:true},
  // { title: '需求人信息', dataIndex: 'demandPersonName', key: 'demandPersonName', hideInSearch: true },
  { title: '需求人/手机', dataIndex: 'demandPerson', key: 'demandPerson', hideInTable: true },
  { title: '归属人', dataIndex: 'createUserName', key: 'createUserName', hideInTable: true },
  { title: '跟进人', dataIndex: 'followUpUserName', key: 'followUpUserName', hideInTable: true },
  { title: '联系人', dataIndex: 'contactName', key: 'contactName', hideInSearch: true },
  // { title: '手机号', dataIndex: 'contactPhone', key: 'contactPhone', hideInSearch: true, width: 150 },
  { title: '需求渠道', dataIndex: 'channelName', key: 'channelName', hideInSearch: true },
  { title: '四级分类', dataIndex: 'fourTypeName', hideInSearch: true,ellipsis:true },
  { title: '需求记录', dataIndex: 'address', key: 'address', hideInSearch: true },
  { title: '需求单状态', dataIndex: 'demandStatus', key: 'demandStatus', valueEnum: {
    1: { text: '待跟进', status: 'Success' },
    2: { text: '已跟进', status: 'Success' },
    3: { text: '已完成', status: 'Success' },
  } },
  { title: '需求单跟进人', dataIndex: 'lastFollowUpName', key: 'lastFollowUpName', hideInSearch: true },
  { title: '服务项目', dataIndex: 'productType', key: 'productType', hideInSearch: true, valueEnum: {
    0: { text: '未知' },
    1: { text: '保洁' },
    2: { text: '搬家' },
    3: { text: '保养' },
    4: { text: '维修' },
  } },
  { title: '金额', dataIndex: 'orderPrice', key: 'orderPrice', valueType: 'money', hideInSearch: true },

  { title: '操作', dataIndex: 'operation', key: 'operation', slotName: 'operation', fixed: 'right', width: 400, hideInSearch: true }
];

// 历史跟进计划列
const historyColumns = [
  { title: 'ID', dataIndex: 'id', key: 'id' },
  { title: '需求单ID', dataIndex: 'demandId', key: 'demandId' },
  { title: '计划日期', dataIndex: 'planDate', key: 'planDate' },
  { title: '完成日期', dataIndex: 'finishDate', key: 'finishDate' },
  { title: '说明', dataIndex: 'planInfo', key: 'planInfo' },
  { title: '操作', dataIndex: 'operation', key: 'operation', slotName: 'operation' }
];

// 需求记录弹窗
const recordModalVisible = ref(false);
const selectedRecord = ref(null);

// 历史跟进计划弹窗
const historyModalVisible = ref(false);
const historyList = ref([]);

// 需求升级弹窗
const upgradeModalVisible = ref(false);
const upgradeForm = ref({
  demandId: '',
  assignUserId: '',
  assignUserName: '',
  remark: ''
});

// 设定跟进任务弹窗
const taskModalVisible = ref(false);
const taskForm = ref({
  demandId: '',
  followUpType: '',
  planDate: '',
  finishDate: '',
  planInfo: ''
});

// 需求详情弹窗
const detailModalVisible = ref(false);
const detailData = ref<any>({
  demandPersonName:'',
  demandPersonPhone: '',
  demandPersonLandlinePhone: '',
  demandPersonTag: [],
  demandPersonAddress:'',
  typeName:'',
  channelName:'',
  fourTypeName:'',
  contactName:'',
  contactPhone:'',
  contactAddress:'',
  reservationTime:'',
  productType:0,
  orderPrice:'',
  requirementRecord:'',
  demandStatus:'',
  carefulRemark:'',
  fileList:[]
});

// 获取支付链接
const handleAcquire = async (record: any) => {
  const response = await getPayUrl({ id: record.id });
  console.log(response);
  if (response) {
    Message.success('支付链接获取成功');
    navigator.clipboard.writeText(response)
      .then(() => {
        Message.success('文本已复制到剪贴板');
      })
      .catch((err) => {
        Message.error('无法复制文本: ', err);
        console.log(err)
      });
  } else {
    Message.error('支付链接获取失败');
  }
};

const showRecordModal = (record) => {
  selectedRecord.value = record;
  recordModalVisible.value = true;
};

// 创建需求
const handleCreate = (record) => {
  router.push({
    name: 'DemandDetail',
    params: { id: '0' }
  });
};

// 操作函数
const handlePay = async (record: any) => {
  console.log(record.id);
  await sendPaySms(record.id);
  console.log('发起支付', record);
  Message.success('短信发送成功');
};
const handleShort = async (record) =>{
 await confirmServiceSms(record.id);
 Message.success('确认成功');
 actionRef.value.reload();
}
const handleUpgrade = (record: any) => {
  upgradeForm.value.demandId = record.id;
  upgradeModalVisible.value = true;
};

const handleUpgradeSubmit = async () => {
  try {
    const response = await saveDemandComplaint(upgradeForm.value);
    if (response) {
      Message.success('需求升级成功');
      upgradeModalVisible.value = false;
    } else {
      Message.error('需求升级失败');
    }
  } catch (error) {
    console.error('需求升级失败', error);
    Message.error('需求升级失败');
  }
};

const handleSetTask = (record: any) => {
  taskForm.value.demandId = record.id;
  taskModalVisible.value = true;
};

const handleTaskSubmit = async () => {
  try {
    const response = await saveDemandFollowUp(taskForm.value);
    if (response) {
      Message.success('跟进任务设定成功');
      taskForm.value = {
        demandId: '',
        followUpType: '',
        planDate: '',
        finishDate: '',
        planInfo: ''
      };
      taskModalVisible.value = false;
    } else {
      Message.error('跟进任务设定失败');
    }
  } catch (error) {
    console.error('跟进任务设定失败', error);
    Message.error('跟进任务设定失败');
  }
};

const handleHistory = async (record: any) => {
  console.log('历史跟进记录', record);
  try {
    const response = await getDemandFollowUpList({
      page: 1,
      size: 10,
      condition: {
        demandId: record.id
      }
    });
    if ('data' in response) {
      historyList.value = response.data.list;
      historyModalVisible.value = true;
    }

  } catch (error) {
    console.error('获取历史跟进计划失败', error);
  }
};

const handleEdit = async (record: any) => {
  console.log('修改', record);
  const detail = await getDemandDetail(record.id);
  console.log(detail, '-detail');
  detailData.value = detail;
  detailModalVisible.value = true;
};

const handleDelete = (record: any) => {
  deleteDemand({ id: record.id }).then(() => {
    Message.success('删除成功');
    actionRef.value.reload();
  });
  console.log('删除', record);
};

const handleHistoryDelete = (record: any) => {
  deleteDemandFollowUp({ id: record.id }).then(() => {
    Message.success('删除成功');
    actionRef.value.reload();
  });
  console.log('删除', record);
};

const handleHistoryDetail = (record: any) => {
  console.log('查看详情', record);
  taskModalVisible.value = true;
  taskForm.value = record;
  // 这里可以跳转到详情页面或者弹出详情模态框
};

const saveDemandForm = () => {
  const obj  = {
    id: detailData.value.id,
    fileList: detailData.value.fileList,
    requirementRecord: detailData.value.requirementRecord,
    demandStatus: detailData.value.demandStatus,

  }
  updateDemandPlan({...obj,...serviceReservationData.value}).then(() => {
    Message.success('保存成功');
  });
};


</script>